/**
 *
 */
package com.apache.ius.common.connectors.impl;

import com.apache.api.api.ApiService;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.service.impl.redis.JedisSsoUtil;
import com.apache.cache.util.Validator;
import com.apache.client.IUSRequestParams;
import com.apache.database.constant.SpringContextLoader;
import com.apache.exception.BusinessException;
import com.apache.ius.able.CacheHelper;
import com.apache.ius.common.annotion.AnntationBean;
import com.apache.ius.common.annotion.BeanFactory;
import com.apache.ius.common.connectors.BeforlerInterceptorAdapter;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Act;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 赋值请求参数
 */
@AnntationBean(name = "setReqParam")
public class SetReqParamAdapterImpl extends BeforlerInterceptorAdapter {

    private ApiService iusService;

    /* (non-Javadoc)
     * @see com.iussoft.portal.common.connectors.InterceptorAdapter#beforPreHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.apache.api.vo.ParamsVo)
     */
    public boolean beforPreHandle(HttpServletRequest request, HttpServletResponse response,
            ParamsVo param) {
        Map<String, Object> resultMap = param.getParams();
        param.setParams("ParamType", "json");
        String modelTypes = String.valueOf(resultMap.get("modelTypes"));
        String ifDataAct = String.valueOf(resultMap.get("ifDataAct"));
        String sqlKeyId = String.valueOf(resultMap.get("sqlKeyId"));//为了照顾最早时的自定义sql，所以需要加此判断。
        String userOwner=null;
        LoginUser loginUser = BeanFactory.getInstance().getLoginUser(request);
        if (Validator.isNull(sqlKeyId) && Validator.isNull(modelTypes)) {
            String pageName = StrUtil.doNull(request.getParameter("pageName"),
                    String.valueOf(param.getParams("pageName")));
            String formName = StrUtil.doNull(request.getParameter("formName"),
                    String.valueOf(param.getParams("formName")));
            if (StrUtil.isNull(formName) || StrUtil.isNull(pageName)) {
                throw new BusinessException("未检测到相应的参数设置，代码号：【" + pageName + ":" + formName + "】");
            }
            String key = formName + "_" + pageName;
            Map map = (Map) CacheHelper.getInstance().getIusParamCache(key);
            if (ToolsUtil.isEmpty(map)) {
                throw new BusinessException("未检测到相应的参数设置，代码号：【" + pageName + ":" + formName + "】");
            }

            String iusId = String.valueOf(map.get("infoId"));
            modelTypes = String.valueOf(map.get("modelTypes"));
            userOwner = String.valueOf(map.get("userOwner"));
            boolean flag = true;
            if (!Validator.isEmpty(loginUser) && Validator.isNotNull(iusId)) {
                flag = this.checkAct(loginUser, iusId);
            }
            if (!flag) {
                throw new BusinessException("您暂时还没有被授予此项操作权限");
            }
            Map params = IUSRequestParams.analyzeParams(map, resultMap);
            resultMap.putAll(params);
            resultMap.put("exportFileName",String.valueOf(map.get("title")));
            resultMap.remove("pageName");
            resultMap.remove("formName");
            param.setParams(resultMap);
        }
        if (modelTypes.contains("sysParamManager")) {//ius参数设置中关联关系去空格
            String relation = String.valueOf(param.getParams("sysParamManager.s_relation"));
            if (StrUtil.isNull(relation)) {
                param.setParams("sysParamManager.relation", StrUtil.doNull( String.valueOf(param.getParams("sysParamManager.relation")).trim(), ""));
            } else {
                param.setParams("sysParamManager.s_relation", StrUtil.doNull(relation.trim(), ""));
            }
            String cloums = String.valueOf(param.getParams("sysParamManager.resultColumn"));
            if (StrUtil.isNotNull(cloums)) {
                param.setParams("sysParamManager.resultColumn", StrUtil.doNull(cloums.trim(), ""));
            }
        }


        //在查询时，默认设置查询参数orgId，根据个人的数据权限查询相应数据
        if("T".equals(ifDataAct)||"T".equals(userOwner)){//判断是否需要添加数据权限
            if (!Validator.isEmpty(loginUser)&&!"1".equals(loginUser.getDelStatus())) {
                String str[] = modelTypes.split(",");
                for (int i = 0; i < str.length; i++) {
                    if (str[i].startsWith("s_")) {
                        String prefix = str[i].substring(2);
                        if (ToolsUtil.isNull(String.valueOf(resultMap.get(prefix + ".wi_orgId")))) {
                            param.setParams(prefix + ".wi_orgId",
                                    loginUser.getDataOrgIds() + loginUser.getUser()
                                            .getOrgId());//如果查多个机构的数据，那么查询该登录人所在机构以及权限机构的数据
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * description:  获取访问权限
     *
     * @param loginUser
     * @param iusId
     * @return
     */
    private boolean checkAct(LoginUser loginUser, String iusId) {
        String cacheKey = "act_ius_" + iusId;
        Object obj = JedisSsoUtil.getInstance().getCacheNameForValue("act_ius_ports",cacheKey);
        ResultEntity entity = null;
        if (Validator.isEmpty(obj)) {
            ParamsVo vo = new ParamsVo();
            vo.setMethodKey("dymicSql");
            vo.setParams("modelTypes", "s_uctActIus");
            vo.setParams("resultType", "objInfo");
            vo.setParams("sqlKeyId", "objInfo");
            vo.setParams("resultObjType", "list");
            vo.setParams("uctActIus.w_iusId", iusId);
            vo.setParams("sysPass", ConfigUtil.getInstance().interfacePass());
            vo.setParams("datasource","plateform");
            entity = getIusService(vo);
            Map<String, Object> whereMap = new HashMap<String, Object>();
//            whereMap.put("uctActIus.w_iusId", iusId);
//            entity = IusPluginUtil.getInstance().select("plateform","list","s_uctActIus",whereMap);

            if (null != entity.getEntity()) {
                JedisSsoUtil.getInstance().setCacheNameForValue("act_ius_ports",cacheKey, entity,300);
            }
        } else {
            entity = (ResultEntity) obj;
        }
        if (null == entity.getEntity()) {
            return true;
        } else {
            log.info("auth [act_ius] query result->"+JSONObject.fromObject(entity));
            List list = (List) entity.getEntity();
            if (list.isEmpty())
                return true;
            Map<String, Act> acts = loginUser.getActMap();
            for (int i = 0; i < list.size(); i++) {
                Map data = (Map) list.get(i);
                String actEname = String.valueOf(data.get("actEname"));
                if (null != acts.get(actEname))
                    return true;
            }
            return false;
        }
    }

    private ResultEntity getIusService(ParamsVo vo){
        if(null == this.iusService) {
            Object obj = SpringContextLoader.getBean("iusService");
            if (obj != null) {
                this.iusService = (ApiService) obj;
            }
        }
        if(null == this.iusService){
            return LoadRpcService.service().doService("iusService",vo.getMethodKey(),"xml",vo.getParams(),null);
        }else{
            return this.iusService.doService(vo);
        }
    }
}
